<?php
class ProductsController extends AppController {
	var $name = 'Products';

    public function axUpload ($no='') {
        if (!$this->_checkLogged('A')) {
            return;
        }

        Configure::write('debug', 0);

        App::import('Vendor', 'Image', array('file'=>'image.class.php'));

        $json = $this->params['form'];
        $name = basename($_FILES['uploadImage']['tmp_name']);

        $img = new Upload($_FILES['uploadImage']);

        if ($no == 1) {
            $img->image_x     = 252;
            $img->image_y     = 561;
            $img->image_ratio = true;
        } else {
            $img->image_x          = 194;
            $img->image_y          = 155;
            $img->image_ratio_crop = true;
        }

        $img->file_max_size      = 4096000;
        $img->allowed            = array('image/jpeg', 'image/pjpeg', 'image/gif', 'image/png');
        $img->file_new_name_body = $name;
        $img->image_min_width    = 64;
        $img->image_min_height   = 64;
        $img->image_resize       = true;
        $img->Process(IMAGES.'tmp'.DS);

        if ($img->processed) {
            $json = array(
                'status'   => 1,
                'filename' => $img->file_dst_name
            );
            $img->Clean();
        } else {
            $json = array(
                'status'  => -1,
                'message' => __($img->error, true)
            );
        }

        $this->set('json', $json);
        $this->render(false, 'json');
    } // axUpload

    public function update () {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $this->data['Product'] = $this->params['form'];

        if ($this->data) {
            $valid = true;

            foreach ($this->data['Product'] as $fieldname=>$value) {
                if (empty($value) && $value != '0' && $fieldname != 'id') {
                    $this->data['Product'][$fieldname] = null;
                }
            }

            $this->Product->set($this->data);

            if ($this->Product->validates() && $valid) { // data validated!
                if ($this->Product->save($this->data)) {
                    $mesg = empty($this->params['form']['id']) ? __('New product has been created successfully!',true) : __('Product has been updated successfully!',true);
                    $json = array(
                        'status' => true,
                        'id'     => $this->Product->id,
                        'mesg'   => $mesg
                    );

                    $img = $this->data['Product']['image'];
                    $thm = $this->data['Product']['thumbnail'];

                    if (file_exists(IMAGES.'tmp'.DS.$img)) {
                        @rename(IMAGES.'tmp'.DS.$img, IMAGES.'products'.DS.$img);
                    }
                    if (file_exists(IMAGES.'tmp'.DS.$thm)) {
                        @rename(IMAGES.'tmp'.DS.$thm, IMAGES.'products'.DS.$thm);
                    }
                } else {
                    $mesg = empty($this->params['form']['id']) ? __('Fail insert product to database at this time, please try again.',true) : __('Fail update product to database at this time, please try again.',true);
                    $err  = ($this->error) ? $this->error : $mesg;
                    $json = array(
                        'status' => false,
                        'mesg'   => $err
                    );
                }
            } else { // invalid data found
                $json = array(
                    'status' => false,
                    'mesg'   => __('Please enter the requested details in the fields pointed out below and try again!', true)
                );
                foreach ($this->Product->invalidFields() as $k=>$v) {
                    $json['error'][] = array('id'=>$k, 'field'=>$k, 'code'=>$v);
                }
            }
        } else {
            $json = array(
                'status' => false,
                'mesg'   => __('no data posted', true)
            );
        }

        $this->response($json);
    } // update

    public function remove () {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $id   = $this->params['form']['id'];
        $data = $this->Product->read(array('thumbnail','image'), $id);

        if ($data == false || count($data) == 0) {
            $json = array(
                'status' => false,
                'error'  => __('Fail delete product, please try again.', true)
            );
            $this->response($json);
            return;
        }

        if (!$this->Product->delete($id)) {
            $json = array(
                'status' => false,
                'error'  => __('Fail delete product, please try again.', true)
            );
            $this->response($json);
            return;
        }

        $path = IMAGES.'products'.DS;

        @unlink($path.$data['Product']['thumbnail']);
        @unlink($path.$data['Product']['image']);

        $json = array('status'=>true, 'message'=>__('Product deleted successfully!',true));
        $this->response($json);
    } // remove

    public function condom () {
        $json   = array();
        $images = $this->Product->find('all', array(
            'conditions' => array('category' => 'c'),
            'recursive'  => -1,
            'order'      => array('order', 'id DESC')
        ));

        foreach ($images as $i=>$p) {
            $json[$i] = $p['Product'];
        }

        $files    = glob(IMAGES.'/cms/condom_*');
        $filename = (count($files) > 0) ? basename($files[0]) : '';

        $this->stylesheet  = am($this->stylesheet, 'sexylightbox/sexylightbox');
        $this->javascripts = am($this->javascripts, 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
         'jquery.easing.1.3', 'jquery.scrollTo-min', 'sexylightbox.v2.3.jquery.min', 'tinymce/tiny_mce_gzip', 'webtoolkit.aim');

        $this->pageTitle = __('Our Products',true);
        $this->set('json', json_encode($json));
        $this->set('category', 'c');
        $this->set('filename', $filename);
    } // condom

    public function accesories () {
        $json   = array();
        $images = $this->Product->find('all', array(
            'conditions' => array('category' => 'm'),
            'recursive'  => -1,
            'order'      => array('order', 'id DESC')
        ));

        foreach ($images as $i=>$p) {
            $json[$i] = $p['Product'];
        }

        $files    = glob(IMAGES.'/cms/accesories_*');
        $filename = (count($files) > 0) ? basename($files[0]) : '';

        $this->javascripts = am($this->javascripts, 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
         'jquery.easing.1.3', 'jquery.scrollTo', 'tinymce/tiny_mce_gzip', 'webtoolkit.aim');

        $this->pageTitle = __('Our Products',true);
        $this->set('json', json_encode($json));
        $this->set('category', 'm');
        $this->set('filename', $filename);
        $this->render('condom');
    } // accesories

    public function shopping () {
        $page   = isset($this->passedArgs['page']) ? $this->passedArgs['page'] : 1;
        $params = array(
            //'conditions' => array('' => ''),
            'recursive'  => -1,
            'fields'     => array('id', 'name', 'price', 'thumbnail'),
            'limit'      => 4
        );
        $this->paginate = $params;

        $this->pageTitle = __('Shopping',true);
        $this->set('cart', $this->Session->read('Cart'));
        $this->set('page', $page);
        $this->set('data', $this->paginate());
    } // shopping

    public function addcart ($id, $page=1) {
        $cart = $this->Session->read('Cart');
        $new  = true;

        if (is_array($cart)) {
            foreach ($cart as $i=>$c) {
                if ($c['id'] == $id) { // repeat item
                    $c['qty']   += 1;
                    $c['total']  = $c['price'] * $c['qty'];

                    $cart[$i] = $c;
                    $new      = false;
                    $this->Session->write('Cart', $cart);
                }
            }
        } else {
            $cart = array();
        }

        if ($new) {
            $data   = $this->Product->read(null, $id);
            $cart[] = array(
                'id'    => $id,
                'name'  => $data['Product']['name'],
                'price' => $data['Product']['price'],
                'thumb' => $data['Product']['thumbnail'],
                'qty'   => 1,
                'total' => $data['Product']['price']
            );
            $this->Session->write('Cart', $cart);
        }

        $this->redirect('/products/shopping/page:'.$page);
    } // addcart
} // ProductsController

?>